
<!DOCTYPE html>
<html lang="en">

  <head>
    <meta charset="utf-8">
    <title>Visual Interface</title>
    <meta name="author" content="NYU UGR Team">
    <link href='http://fonts.googleapis.com/css?family=Open+Sans:400,300,400italic,700' rel='stylesheet' type='text/css'>
    <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro" rel="stylesheet">
    <link href="static/css/scratchstyle-light.css" rel="stylesheet" type="text/css">
    <!-- D3.js and jQuery source -->
    <script src="https://d3js.org/d3.v4.min.js"></script>
    <!-- <script type="text/javascript" src="static/js/d3.min.js"></script> -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <!-- <script type="text/javascript" src="static/js/jquery-3.3.1.min.js"></script> -->
    <!-- SVG scripts -->
    <script type="text/javascript" src="static/js/main_graph.js"></script>
    <script type="text/javascript" src="static/js/percentage_bar.js"></script>
    <script type="text/javascript" src="static/js/squares.js"></script>
  </head>

  <body>
    <div class="main">
      <div class="left-sidebar">
        <header class="site-header">
          <h1><a href="intro">FICO CHALLENGE</a></h1>
        </header>
        <nav class="left-nav">
          <ul>
            <li><a href="global">GLOBAL EXPLANATION</a></li>
            <li><a href="individual">LOCAL EXPLANATIONS</a></li>
          </ul>
        </nav>
        <!-- Search box -->
        <div class="input-group">
          <input id="search-bar" type="text" class="form-control" placeholder="ID number" name="srch-term" autocomplete="off"
                 onkeydown="formHandle(event)">
        </div>
        <nav class="id-list">
        </nav>
      </div>

      <div class="right-side" id="demo">


        <img src="static/images/ind_instructions.png" id="ind-instruction">



        <div id = "header-container">
          <table class="right-header" align="center">
            <tr>
                <td id="id-display">

                </td>
                <td id="category-display">
                  <div id="container">
                    <div class="cat-text"></div>
                    <img id="category-img">
                  </div>
                </td>

                <td id="space"></td>
                <td id="model-display">

                </td>
            </tr>
          </table>
        </div>
        <div class="d3-space">
          <!-- D3 graphs -->
        </div>
          <div id="txt-space-key">
          </div>
          <div id="txt-space-chg">
          </div>
          <div id="similar-samples">
          </div>
          <!-- Text explanation -->

        </div>
      </div>
    </div>

    <script>

      var dark_shade = "rgb(177, 196, 209)";
      var light_shade = "white";


      function addSquare(elemn, category, size) {
        var sqr = document.createElement("img");
          if (category == "FN"){
            sqr.src="static/images/square2-min.jpg";
          }
          else if (category == "TN"){
            sqr.src="static/images/square4-min.jpg";
          }
          else if (category == "FP"){
            sqr.src="static/images/square1-min.jpg";
          }
          else if (category == "TP"){
            sqr.src="static/images/square3-min.jpg";
          }
          else if (category == "NA"){
            sqr.src="static/images/square5-min.jpg";
          }
          sqr.height=size;
          sqr.width=size;
          sqr.id = "category-img";
          sqr.style.margin = "0px 0px 0px 0px";
          document.getElementById(elemn).append(sqr);
      }

      function formHandle(event) {
        if (event.which == 13 || event.keyCode == 13){
          makeRequest('form', 0);
          return false;
        }
      }

      function densityCheckHandle(event) {
        makeRequest("check-density", 0);
        return false;
      }

      function monotCheckHandle(event) {
        makeRequest("check-monot", 0);
        return false;
      }

      function sortCheckHandle(event) {
        makeRequest("check-sort", 0);
        return false;
      }

      var txtFile;
      function fetch_csv(){
        txtFile = new XMLHttpRequest();
        txtFile.onreadystatechange = initContents;
        txtFile.open("GET", "static/data/pred_data_x.csv");
        txtFile.send()
      }

      var pre_array = [];
      function initContents() {
        if (txtFile.readyState === XMLHttpRequest.DONE) {
          if (txtFile.status === 200) {
            var rows = txtFile.responseText.split("\n");
            for (var i = 0; i < rows.length; i++) {
              var cells = rows[i].split(",");
              pre_array.push(cells);
            }
            //console.log("CSV");
            prep_content(add_loader, id_list, add_images, create_buttons, from_global);
          }
        }
      }

      var httpRequest;
      function makeRequest(source, sample) {
        httpRequest = new XMLHttpRequest();
        if (!httpRequest) {
          alert('Giving up :( Cannot create an XMLHTTP instance');
          return false;
        }
        document.getElementById("txt-space-key").innerHTML = "";
        document.getElementById("txt-space-chg").innerHTML = "";
        document.getElementById("similar-samples").innerHTML = "";
        if (source == 'form') {
          var s = document.getElementById("search-bar").value;
          document.getElementById("search-bar").value="";
        }
        else if (source == 'list') {
          var s = sample.id.substring(5);
        }
        else if (source == "global") {
          var s = sample.toString();
        }
        else if (source == "prop-button"){
          var s = document.getElementById("id-display").innerHTML.substring(4);
        }
        else if (source == "similar"){
          var s = sample.innerHTML;
        }

        var monot = "False";
        if (document.getElementById("monot-button").style.backgroundColor == dark_shade){
          monot = "True";
        }
        var sort = "False";
        if (document.getElementById("sort-button").style.backgroundColor == dark_shade){
          sort = "True";
        }

        httpRequest.onreadystatechange = alertContents;
        httpRequest.open('GET', 'instance?sample='+s+'&monot='+monot+'&sort='+sort);
        httpRequest.send();
        return false;
      }

      function alertContents() {

        if (httpRequest.readyState === XMLHttpRequest.OPENED) {
          var right = document.getElementById("demo");
          //console.log(right.childNodes[1]);
          if (right.childNodes[1].id == "ind-instruction"){
            right.removeChild(right.childNodes[1]);
          }
          document.getElementById("demo").style.textAlign = "center";

          document.getElementsByClassName("d3-space")[0].innerHTML="";
          var load_wrap = document.createElement("div");
          load_wrap.className = "loader_wrap";
          var loader = document.createElement("div");
          loader.className = "lds-dual-ring";
          load_wrap.append(loader);
          document.getElementsByClassName("d3-space")[0].append(load_wrap);
        }

        else if (httpRequest.readyState === XMLHttpRequest.DONE) {
          if (httpRequest.status === 200) {
            //Do stuff with the response

            document.getElementsByClassName("d3-space")[0].innerHTML="";

            if (document.getElementsByClassName("ind-header")[0].style.display == "none"){
              document.getElementsByClassName("ind-header")[0].style.display = "table";
            }


            var resp_arr = httpRequest.responseText.split('~');
            var testData = [];
            var densityData = [];
            for (i=0; i<23; i++){
              testData.push(JSON.parse(resp_arr[i]));
            }
            for (i=0; i<23; i++){
              densityData.push(JSON.parse(resp_arr[i+23]));
            }

            var resp = JSON.parse(resp_arr[46]);

            var index = resp['sample'].toString();
            var trans_sample = resp['trans_sample'].toString();
            var good_percent = resp['good_percent'];
            var correct = parseInt(resp['model_correct']);
            var category = resp['category'];
            var result = resp['predicted'];
            var text_exp = resp['text_exp'];
            var similar_ids = resp['similar_ids'];
            var disp_percent = good_percent;
            document.getElementById("id-display").innerHTML = "ID: " + index;
            document.getElementById("model-display").innerHTML = "";
            var image_x = document.getElementById('category-img')
            image_x.parentNode.removeChild(image_x);
            addSquare("container", category, 45);
            draw_percent_bar(disp_percent);
            document.getElementsByClassName("cat-text")[0].innerHTML = category;
            document.getElementsByClassName("d3-space")[0].innerHTML = "";

            if (trans_sample == '-9') {
              document.getElementsByClassName("d3-space")[0].innerHTML = "";
              var error = document.createElement("img");
              error.src = "static/images/errors.png";
              error.id = "error-img";
              document.getElementsByClassName("d3-space")[0].append(error);
              document.getElementsByClassName("ind-text")[0].innerHTML = "";
              return;
            }

            // Text explanation
            document.getElementById("txt-space-key").innerHTML = "";
            document.getElementById("txt-space-chg").innerHTML = "";
            document.getElementById("similar-samples").innerHTML = "";
            var p_exp = document.createElement("p");
            var line = "";
            var start = 0;
            var end = 0;
            var change_good = text_exp.indexOf("Suggested Changes");
            var change_bad = text_exp.indexOf("Warnings");
            var keys = text_exp.indexOf("Key Features");
            start = text_exp.indexOf("\n");
            var line_1 = text_exp.substring(0, start);
            var per_m = document.getElementsByClassName("per_marker")[0].innerHTML;
            line_1 = line_1.replace("###", Math.round(disp_percent*100).toString());

            document.getElementsByClassName("ind-text")[0].innerHTML = line_1;

            for (j=text_exp.indexOf("\n")+1; j<text_exp.length; j++){
              if (text_exp[j] == "\n" || j==text_exp.length-1){
                var p_exp = document.createElement("p");
                end = j;
                line = text_exp.substring(start,end+1);
                p_exp.innerHTML = line;

                if (line.indexOf("Suggested Changes")>-1 || line.indexOf("Warnings")>-1 || line.indexOf("Key Features")>-1){
                  p_exp.style.fontWeight = "bold";
                  p_exp.style.fontSize = "13px";
                }
                if (line.indexOf(":")>-1){
                  p_exp.style.marginBottom = "5px";
                }

                if (line.length > 1 && change_good == -1 && change_bad == -1){
                  document.getElementById("txt-space-key").append(p_exp);

                }
                else if (line.length > 1 && keys == -1){
                  document.getElementById("txt-space-chg").append(p_exp);

                }
                else if (line.length > 1 && j<Math.max(change_good, change_bad)){
                  document.getElementById("txt-space-key").append(p_exp);

                }
                else if (line.length > 1 && j>=Math.max(change_good, change_bad)){
                  document.getElementById("txt-space-chg").append(p_exp);

                }
                start = end+1;
              }
            }

            if (similar_ids.length > 0){
              var sim_h = document.createElement("p");
              sim_h.style.fontSize = "13px";
              sim_h.style.fontWeight = "bold";
              sim_h.innerHTML = "Instances where changes have been applied:";
              document.getElementById("similar-samples").append(sim_h);

              //console.log(similar_ids);
              for (j=0; j<similar_ids.length; j++){
                  var sim_p = document.createElement("a");
                  line = similar_ids[j];
                  sim_p.innerHTML = line;
                  sim_p.onclick = function () { makeRequest('similar', this); };
                  document.getElementById("similar-samples").append(sim_p);
              }

            }


            if (document.getElementById("density-button").style.backgroundColor == dark_shade){


              draw_graph(testData, densityData, result);
            }
            else {
              draw_graph(testData, "no", result);
            }


          } else {
            alert('HttpRequest Error')
          }
        }
      }

      function prep_content(callback0, callback1, callback2, callback3, callback4) {

        setTimeout(function(){ callback1();}, 50);

        setTimeout(function(){ callback3();}, 50);

        callback4();
      }

      function add_loader() {
        document.getElementsByClassName("id-list")[0].innerHTML="";
        var load_wrap = document.createElement("div");
        load_wrap.className = "loader_wrap";
        var loader = document.createElement("div");
        loader.className = "lds-dual-ring";
        load_wrap.append(loader);
        document.getElementsByClassName("id-list")[0].append(load_wrap);
      }

      function id_list (){

        var samples = 10459;
        var list_cont = document.createElement("ul");
        for (i = 1; i <= samples; i++) {
          var para = document.createElement("li");
          para.innerHTML = "ID " + i.toString();
          para.id = "link-" + i.toString();
          para.onclick = function () { makeRequest('list', this); };
          var li_div = document.createElement("div");
          li_div.style.width = "75px";
          li_div.style.float = "right";
          li_div.style.margin = "0px 25px 0px 0px";
          li_div.id = "link-div-" + i.toString();


          var sqr = document.createElement("img");

          if (pre_array[i][2].trim() == "FN"){
            sqr.src="static/images/square2-min.jpg";
          }
          else if (pre_array[i][2].trim() == "TN"){
            sqr.src="static/images/square4-min.jpg";
          }
          else if (pre_array[i][2].trim() == "FP"){
            sqr.src="static/images/square1-min.jpg";
          }
          else if (pre_array[i][2].trim() == "TP"){
            sqr.src="static/images/square3-min.jpg";
          }
          else if (pre_array[i][2].trim() == "NA"){
            sqr.src="static/images/square5-min.jpg";
          }
          sqr.height="15";
          sqr.width="15";
          sqr.style.borderRadius = "50%";
          sqr.style.verticalAlign = "middle";
          sqr.style.margin = "4px 0px 0px 0px";
          sqr.style.float = "left";
          sqr.className = "mini-category-img";
          var link_string = pre_array[i][3] + "\xa0 \xa0"  + pre_array[i][4];
          li_div.innerHTML = link_string;
          li_div.append(sqr);

          para.append(li_div);
          list_cont.append(para);
        }
        //console.log("LIST");

        setTimeout(function(){
          document.getElementsByClassName("id-list")[0].innerHTML="";
          document.getElementsByClassName("id-list")[0].append(list_cont);}, 150);


      }

      function add_images() {

        for (var i = 1; i < pre_array.length-2; i++) {

          var sqr = document.createElement("img");
          if (pre_array[i][2].trim() == "FN"){
            sqr.src="static/images/square2-min.jpg";
          }
          else if (pre_array[i][2].trim() == "TN"){
            sqr.src="static/images/square4-min.jpg";
          }
          else if (pre_array[i][2].trim() == "FP"){
            sqr.src="static/images/square1-min.jpg";
          }
          else if (pre_array[i][2].trim() == "TP"){
            sqr.src="static/images/square3-min.jpg";
          }
          else if (pre_array[i][2].trim() == "NA"){
            sqr.src="static/images/square5-min.jpg";
          }
          sqr.height="15";
          sqr.width="15";
          sqr.style.borderRadius = "50%";
          sqr.style.verticalAlign = "middle";
          sqr.style.margin = "4px 0px 0px 0px";
          sqr.style.float = "left";
          sqr.className = "mini-category-img";
          var link_string = pre_array[i][3] + "\xa0 \xa0"  + pre_array[i][4];
          document.getElementById("link-div-"+i.toString()).innerHTML = link_string;
          document.getElementById("link-div-"+i.toString()).append(sqr);

        }
        //console.log("IMGS");
      }

      function flip_property(elemn) {

        if (elemn.style.backgroundColor == dark_shade) {
          elemn.style.backgroundColor = light_shade;
        }
        else {
          elemn.style.backgroundColor = dark_shade;
        }

        makeRequest("prop-button", 0);
      }

      function create_buttons(){
        //console.log("buttons");
        var ind_header = document.createElement("table");
        var row = document.createElement("tr");
        ind_header.className = "ind-header";

        var ind_text = document.createElement("td");
        ind_text.className = "ind-text";
        ind_text.innerHTML = "";

        var btn_td = document.createElement("td");
        btn_td.className = "btn-td";
        var check_group = document.createElement("div");
        check_group.className = "check-group";

        var density_button = document.createElement("button");
        var monot_button = document.createElement("button");
        var sort_button = document.createElement("button");

        density_button.className = "prop-button";
        monot_button.className = "prop-button";
        sort_button.className = "prop-button";

        density_button.id = "density-button";
        monot_button.id = "monot-button";
        sort_button.id = "sort-button";

        density_button.innerHTML = "Density";
        monot_button.innerHTML = "Monotonicity";
        sort_button.innerHTML = "Sort";

        density_button.style.backgroundColor = dark_shade;
        monot_button.style.backgroundColor = light_shade;
        sort_button.style.backgroundColor = light_shade;

        density_button.onclick = function(){flip_property(this);};
        monot_button.onclick = function(){flip_property(this);};
        sort_button.onclick = function(){flip_property(this);};

        check_group.append(density_button);
        check_group.append(monot_button);
        check_group.append(sort_button);
        btn_td.append(check_group);
        row.append(ind_text);
        row.append(btn_td);
        ind_header.append(row);
        ind_header.style.display = "none";
        var right_side = document.getElementsByClassName("right-side")[0];
        right_side.insertBefore(ind_header, right_side.childNodes[4]);
      }

      function from_global() {
        var url_str = window.location.href;
        var initial_sample = parseInt(url_str.substring(url_str.indexOf("sample")+7));
        //console.log(initial_sample);
        if (isNaN(initial_sample)) {
          
          document.getElementById("ind-instruction").style.display = "block";
        }
        else {
          setTimeout(function(){makeRequest("global", initial_sample);}, 50);
        }
      }


      add_loader();
      fetch_csv();

    </script>

  </body>

</html>
